package com.lxq.cloud.config;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.GatewayFilterSpec;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.cloud.gateway.route.builder.UriSpec;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.function.Function;


@Configuration
public class GlobalConfig {
    @Bean
    public RouteLocator getRouteLocator(RouteLocatorBuilder builder){
//        builder.routes().route("monitor-hello", predicateSpec ->
//                predicateSpec.path("/hello2").uri("http://localhost:1880/hello2")).build();
//        return builder.routes().build();
        return builder.routes().route(predicateSpec -> predicateSpec.path("/sleep_req")
                .uri("http://localhost:1880"))
                .route(predicateSpec -> predicateSpec
                        .path("/hello2")
                        .and()
                        .before(ZonedDateTime.of(2021,10,25,
                                23,53,30,0, ZoneId.systemDefault()))
                        .and()
                        .header("role","admin")
                        .filters(gatewayFilterSpec -> gatewayFilterSpec.filter((exchange, chain) -> {
                            var request=exchange.getRequest();
                            var username=request.getQueryParams().get("country").get(0);
                            System.out.println("country="+username);
                            if (!"china".equals(username)){
                                System.err.println("非法用户，叉出去！");
                                exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
                                return exchange.getResponse().setComplete();
                            }
                            return chain.filter(exchange);
                        }))
                        .uri("lb://CLOUD-MONITOR"))
                .build();
    }
}
